﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Web.Mvc;
using Vit.Common.Extensions;

namespace Vit.Web.Data
{
    public abstract class EntitySourceProvider<TContext, TEntity> : IDataSourceProvider
        where TContext : DataContext, new()
        where TEntity : class, new()
    {
        #region IDataSourceProvider<TEntity> Members

        public abstract string GetDisplayText(params object[] ids);

        public virtual object GetData(params object[] paras)
        {
            var rule = DataRule<TContext, TEntity>.Create();
            return rule.Query(null);
        }

        public virtual IEnumerable<SelectListItem> GetListItems(params object[] paras)
        {
            var data = GetData() as IEnumerable<TEntity>;
            return data.Cast<TEntity, SelectListItem>(delegate(TEntity entity)
            {
                return new SelectListItem()
                {
                    Text = GetListItemText(entity),
                    Value = GetListItemValue(entity)
                };
            });
        }

        public Type EntityType
        {
            get { return typeof(TEntity); }
        }

        #endregion

        protected abstract string GetListItemText(TEntity entity);
        protected abstract string GetListItemValue(TEntity entity);
    }
}
